package other;

import java.util.Arrays;
import java.util.HashMap;

public class TwoSum_1 {

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 17;
        //int[] result = twoSum_1(nums, target);
        int[] result = twoSum_2(nums, target);
        System.out.println(Arrays.toString(result).replace(" ", ""));
    }

    // 暴力解法
    private static int[] twoSum_1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    // hash表解法
    private static int[] twoSum_2(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
